const moment = require('moment')
const path = require('path')
const fs = require('fs')
const express = require('express')
const model = require('./model')
let router = express.Router()


let dataPath = path.join(__dirname, './data/data.json')
router.get(['/', '/index'], (req, res) => {
  model.find((err, ret) => {
    if (err) {
      console.log('查询失败');

    } else {
      // console.log(ret);
      ret.sort((a, b) => {
        // 时间越后越靠前
        return b.id - a.id
      })
      res.render('index.html', { list: ret })
    }
  })
})


router.get('/add.html', (req, res) => {
  res.sendFile(path.join(__dirname, '/pages/add.html'))
})
router.get('/submit', (req, res) => {
  let newmodel = new model({
    id: +new Date(),
    nickname: req.query.nickname,
    title: req.query.tittle,
    content: req.query.content,
    created: moment().format('YYYY年MM月DD日 HH:mm:ss')
  })
  newmodel.save((err, ret) => {
    if (err) {
      console.log('查询失败');
    } else {
      console.log(ret.id);
      res.redirect('/')
    }
  })
})

router.post('/submit', (req, res) => {
  console.log(req.body);
  let newmodel = new model({
    id: +new Date(),
    nickname: req.body.nickname,
    title: req.body.title,
    content: req.body.content,
    created: moment().format('YYYY年MM月DD日 HH:mm:ss')
  })
  newmodel.save((err, ret) => {
    if (err) {
      console.log('查询失败');
    } else {
      console.log(ret.id);
      res.redirect('/')
    }
  })
})
router.get('/delete', (req, res) => {
  let id = req.query.id
  model.remove({
    id: id
  }, function (err, ret) {
    if (err) {
      console.log("删除失败");
      res.redirect('/')
    } else {
      console.log("删除成功");
      console.log(ret);
      res.redirect('/')
    }
  })
})

module.exports = router